<template>
  <div class="history">
    <van-nav-bar
      title="查旧账"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 搜索框 -->
    <div class="search-bar">
      <van-search
        v-model="searchText"
        placeholder="搜索客户名称"
        shape="round"
        background="transparent"
      />
    </div>

    <!-- 历史记录列表 - 按日期分组 -->
    <div class="record-list">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div v-for="(group, date) in groupedRecords" :key="date" class="record-group">
          <div class="date-header">{{ formatDate(date) }}</div>
          
          <div 
            v-for="record in group" 
            :key="record.id"
            class="record-item"
            @click="navigateToCustomerOrders(record.date, record.customerId)"
          >
            <div class="customer-info">
              <img :src="record.customerAvatar" alt="avatar" class="avatar">
              <div class="info-content">
                <div class="name">{{ record.customerName }}</div>
                <div class="date-time">
                  <span class="time">{{ record.time }}</span>
                  <span class="divider">·</span>
                  <span class="count">{{ formatRecordCount(record) }}</span>
                </div>
              </div>
            </div>
            <div class="order-amount">
              <span class="amount">¥{{ record.totalAmount.toFixed(2) }}</span>
              <van-icon name="arrow" />
            </div>
          </div>
        </div>
      </van-list>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

// 定义类型
interface Product {
  id: number;
  name: string;
  quantity: number;
  price: number;
}

interface OrderRecord {
  id: number;
  customerId: number;
  customerName: string;
  customerAvatar: string;
  date: string;
  time: string;
  products: Product[];
  totalAmount: number;
}

interface GroupedRecords {
  [date: string]: OrderRecord[];
}

const router = useRouter()
const searchText = ref('')
const loading = ref(false)
const finished = ref(false)

// 模拟数据 - 更多测试数据
const records = ref<OrderRecord[]>([
  {
    id: 1,
    customerId: 1,
    customerName: '张大姐',
    customerAvatar: '/avatars/1.png',
    date: '2024-01-20',
    time: '14:30',
    products: [
      { id: 1, name: '康师傅红烧牛肉面', quantity: 2, price: 4.5 },
      { id: 2, name: '统一老坛酸菜面', quantity: 1, price: 4.0 },
    ],
    totalAmount: 19.00
  },
  {
    id: 2,
    customerId: 4,
    customerName: '李阿姨',
    customerAvatar: '/avatars/4.png',
    date: '2024-01-20',
    time: '16:45',
    products: [
      { id: 3, name: '可口可乐', quantity: 2, price: 3.5 },
      { id: 4, name: '薯片', quantity: 1, price: 8.0 },
    ],
    totalAmount: 15.00
  },
  {
    id: 3,
    customerId: 2,
    customerName: '老刘',
    customerAvatar: '/avatars/2.png',
    date: '2024-01-20',
    time: '09:15',
    products: [
      { id: 5, name: '香辣方便面', quantity: 3, price: 4.0 },
    ],
    totalAmount: 12.0
  },
  {
    id: 4,
    customerId: 3,
    customerName: '王师傅',
    customerAvatar: '/avatars/3.png',
    date: '2024-01-19',
    time: '18:30',
    products: [
      { id: 6, name: '矿泉水', quantity: 2, price: 2.0 },
    ],
    totalAmount: 4.0
  },
  {
    id: 5,
    customerId: 5,
    customerName: '赵大爷',
    customerAvatar: '/avatars/5.png',
    date: '2024-01-19',
    time: '10:20',
    products: [
      { id: 7, name: '牛奶', quantity: 1, price: 5.5 },
      { id: 8, name: '面包', quantity: 2, price: 4.0 },
    ],
    totalAmount: 13.5
  },
  {
    id: 6,
    customerId: 6,
    customerName: '小张',
    customerAvatar: '/avatars/6.png',
    date: '2024-01-18',
    time: '20:15',
    products: [
      { id: 9, name: '啤酒', quantity: 6, price: 5.0 },
      { id: 10, name: '花生', quantity: 2, price: 3.5 },
    ],
    totalAmount: 37.0
  },
])

// 过滤记录
const filteredRecords = computed(() => {
  if (!searchText.value) return records.value
  
  return records.value.filter(record => 
    record.customerName.includes(searchText.value)
  )
})

// 按日期分组记录
const groupedRecords = computed(() => {
  const grouped: GroupedRecords = {}
  
  filteredRecords.value.forEach(record => {
    if (!grouped[record.date]) {
      grouped[record.date] = []
    }
    grouped[record.date].push(record)
  })
  
  // 按日期倒序排序
  return Object.keys(grouped)
    .sort((a, b) => new Date(b).getTime() - new Date(a).getTime())
    .reduce((result: GroupedRecords, date) => {
      result[date] = grouped[date]
      return result
    }, {})
})

// 格式化日期
const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)
  
  // 格式化为年-月-日
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const formattedDate = `${year}年${month}月${day}日`
  
  // 检查是否是今天或昨天
  if (date.toDateString() === today.toDateString()) {
    return `今天 (${formattedDate})`
  } else if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 (${formattedDate})`
  } else {
    return formattedDate
  }
}

// 格式化记录数量
const formatRecordCount = (record: OrderRecord): string => {
  return `${record.products.length}笔交易`
}

// 跳转到客户订单详情页面
const navigateToCustomerOrders = (date: string, customerId: number): void => {
  router.push(`/customer-orders/${date}/${customerId.toString()}`)
}

// 加载更多
const onLoad = () => {
  // 模拟加载更多逻辑
  setTimeout(() => {
    finished.value = true
    loading.value = false
  }, 500)
}
</script>

<style lang="scss" scoped>
.history {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;

  .search-bar {
    padding: 8px 16px;
    background: #f7f8fa;
  }

  .record-list {
    flex: 1;
    overflow-y: auto;
    padding: 0 16px;
    margin-bottom: 16px;
    
    .record-group {
      margin-bottom: 20px;
      
      .date-header {
        padding: 8px 12px;
        background-color: #f2f3f5;
        border-radius: 8px;
        margin-bottom: 8px;
        font-size: 14px;
        font-weight: 500;
        color: #323233;
      }
    }

    .record-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: #fff;
      padding: 16px;
      margin-bottom: 12px;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

      &:active {
        background-color: #f9f9f9;
      }

      .customer-info {
        display: flex;
        align-items: center;

        .avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          object-fit: cover;
          margin-right: 12px;
        }

        .info-content {
          .name {
            font-size: 16px;
            font-weight: 500;
            color: #323233;
            margin-bottom: 4px;
          }

          .date-time {
            font-size: 13px;
            color: #969799;
            
            .divider {
              margin: 0 4px;
            }
          }
        }
      }

      .order-amount {
        display: flex;
        align-items: center;

        .amount {
          font-size: 16px;
          font-weight: bold;
          color: #ee0a24;
          margin-right: 8px;
        }
      }
    }
  }
}
</style> 